﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Web;
using System.Threading;
using System.IO;
using MDF.Cacher.Managements;
using MDF.Worker;
using TGVR_Boot.Workers;
using MDF.Logger.Managements;
using MDF.Requesting;
using MDF.Utilites.Helper;
using System.Globalization;
using System.Net;
using TGVR.DataHelper.BussinessObject.BookingSystem;
using TGVR.DataHelper.BussinessLogic.BookingSystem;
using TGVR.DataHelper.BussinessObject;

namespace TGVR_Boot
{
    public class JetstarBoot : IBoot
    {

        Requester m_request = new Requester();

        string m_strViewState = "";

        public string resnumber = "";

        public string thanhtien = "";

        public string GetError()
        {
            return m_error;
        }

        private DateTime HoldToDate = DateTime.Now;
        public DateTime GetHoldToDate()
        {
            return HoldToDate;
        }

        public Dictionary<string, string> lstResultHTML = new Dictionary<string, string>();

        /// <summary>
        /// Lấy mã vé
        /// </summary>
        /// <returns></returns>
        public string GetCode()
        {
            return resnumber;
        }
        /// <summary>
        /// Lấy tổng tiền
        /// </summary>
        /// <returns></returns>
        public int GetTotal()
        {
            try
            {
                if (!string.IsNullOrEmpty(thanhtien))
                    return Int32.Parse(thanhtien.Replace(".", ""));
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Jet: Cant get total price!", ex);
            }

            return 0;
        }

        string viewstate = "";

        void GetThongTinSauKhiDatVe(string html)
        {
            HtmlDocument docDepart = new HtmlDocument();
            docDepart.LoadHtml(html);
            try
            {
                //new
                //data-transactionpnr
                var nodesresnumber = docDepart.DocumentNode.SelectNodes("//*[@id=\"datalayer-itinerary-data\"]");
                resnumber = nodesresnumber[0].Attributes["data-transactionpnr"].Value;
                //var nodestotalmoney = docDepart.DocumentNode.SelectNodes("//*[@class=\"ChargesTotal\"]//td[2]");

                thanhtien = nodesresnumber[0].Attributes["data-BookingTotalPrice"].Value;
                thanhtien = thanhtien.Substring(0, thanhtien.IndexOf('.'));
                /*
                 * //Old
                //datalayer-itinerary-data
                var nodesresnumber = docDepart.DocumentNode.SelectNodes("//*[@id=\"datalayer-itinerary-data\"]");
                resnumber = nodesresnumber[0].Attributes["data-transaction-pnr"].Value;
                //var nodestotalmoney = docDepart.DocumentNode.SelectNodes("//*[@class=\"ChargesTotal\"]//td[2]");

                thanhtien = nodesresnumber[0].Attributes["data-booking-total-price"].Value;
                thanhtien = thanhtien.Substring(0, thanhtien.IndexOf('.'));
                 * */


            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Jetstar: Can not get code + money", ex);
            }
            try
            {
                //<booking pnr="FD1VXD" status="hold" holdDate="12 Thg6, 2014 12:03 CH GMT" paymentHours="48" outstandingBalance="991.000">
                //AM GMT
                var timehold = docDepart.DocumentNode.SelectNodes("//booking")[0].Attributes["holdDate"].Value;
                var timeholdNew = timehold.Replace(" CH GMT", "")
                                            .Replace(" PM GMT", "")
                                            .Replace(" AM GMT", "")
                                            .Replace(" SA GMT", "")
                                            .Replace(" Thg", "/")
                                            .Replace(", ", "/");
                HoldToDate = DateTime.ParseExact(timeholdNew, "d/M/yyyy HH:mm", CultureInfo.InvariantCulture);
                if (timehold.IndexOf("PM") > -1 || timehold.IndexOf("CH") > -1)
                {
                    HoldToDate = HoldToDate.AddHours(19);
                }
                else
                {
                    HoldToDate = HoldToDate.AddHours(7);
                }
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Jetstar: Can not get HoldToDate", ex);
            }
        }
        string html = "";
        private string m_error;

        private bool Login()
        {
            try
            {
                Requester stRequest = m_request;
                string html = stRequest.GetHtmlFromResponse(stRequest.GetData("https://book.jetstar.com/TradeLoginAgent.aspx"));
                string strLinkLogin = "https://book.jetstar.com/NewTradeLoginAgent.aspx";
                string strData = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUBMGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFM01lbWJlck5ld1RyYWRlTG9naW5Mb2dpbkFnZW50VmlldyRtZW1iZXJfUmVtZW1iZXJtZRIa6JIDpyg4u3VChloSe0QpildR&pageToken=&ControlGroupNewTradeLoginAgentView%24AgentNewTradeLoginView%24TextBoxUserID=Jethgv2045&ControlGroupNewTradeLoginAgentView%24AgentNewTradeLoginView%24PasswordFieldPassword=Dly%261244&ControlGroupNewTradeLoginAgentView%24AgentNewTradeLoginView%24ButtonLogIn=";
                var respones = stRequest.PostData(strLinkLogin, strData);
                html = stRequest.GetHtmlFromResponse(respones);
                if (respones.ResponseUri.AbsoluteUri.IndexOf("https://book.jetstar.com/TradeSalesHome.aspx") == -1)
                {
                    LogManager.GetInstance().Error("Jetstart: Login fail!");
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Jetstart: Login error!", ex);
                return false;
            }

        }

        public int MakeBooking(BK_Booking booking, BK_Passenger[] passenges, BK_Ticket tkDepart, BK_Ticket tkReturn, int _iUserID)
        {
            bool isBackReturnToDepart = false;
            if (tkDepart == null && tkReturn != null)//2 chieu # hang
            {
                isBackReturnToDepart = true;
                tkDepart = tkReturn;
                tkReturn = null;
            }
            string emailDefault = "thegioivere@gmail.com";
            try
            {
                int iDayTimeOut = Int32.Parse(SettingBUS.Current.GetSetting(-1, "TimeoutBookJetstar").Value);

                if (tkDepart.StartDate.AddHours(iDayTimeOut) <= DateTime.Now)
                {
                    LogManager.GetInstance().Warn("Jetstar: Qua han book ve");
                    return (int)BookingStatus.OUTOFBOOKING;
                }

                #region 1.Đăng nhập
                if (!this.Login())
                {
                    return (int)BookingStatus.NOTLOGIN;
                }

                #endregion

                #region 2.Tìm vé

                //1: nguoi lon, 2: tre em, 3: tre so sinh
                string strRound = tkReturn != null ? "RoundTrip" : "OneWay";
                int iAdut = passenges.Count(m => m.TypeID == 1);
                int iChild = passenges.Count(m => m.TypeID == 2);
                int iBaby = passenges.Count(m => m.TypeID == 3);
                DateTime? dtNull = null;

                string strKeywordDel = "JetstarBoot_Search" + booking.FromCity + "_" + booking.ToCity + tkDepart.StartDate.ToString("_MM_dd_yyyy") +
                (tkReturn != null ? tkReturn.StartDate.ToString("_MM_dd_yyyy") : "") + iAdut.ToString() + iChild.ToString() + iBaby.ToString() + "_User_" + _iUserID;
                CacheManager.GetInstance().Delete(strKeywordDel);
                var lstTickets = Search(booking.FromCity, booking.ToCity, tkDepart.StartDate, tkReturn != null ? tkReturn.StartDate : dtNull, iAdut, iChild, iBaby, tkDepart.IsInter, _iUserID);
                int indexvedi = -1, indexveve = -1;
                for (int i = 0; i < lstTickets.Count; i++)
                {
                    if (lstTickets[i].FlightNo.Replace(" ", "").ToLower() == tkDepart.FlightNo.Replace(" ", "").ToLower() && lstTickets[i].TypeWay == "Out" && lstTickets[i].StartDate.ToString("ddMMyyyyHHmm") == tkDepart.StartDate.ToString("ddMMyyyyHHmm"))
                    {
                        indexvedi = i;
                    }
                    else
                        if (tkReturn != null && lstTickets[i].FlightNo.Replace(" ", "").ToLower() == tkReturn.FlightNo.Replace(" ", "").ToLower() && lstTickets[i].TypeWay == "In" && lstTickets[i].StartDate.ToString("ddMMyyyyHHmm") == tkReturn.StartDate.ToString("ddMMyyyyHHmm"))
                        {
                            indexveve = i;
                        }
                }

                if (lstTickets == null || lstTickets.Count == 0)
                {
                    return (int)BookingStatus.NORESULTFIND;// Lỗi tìm vé
                }

                if (indexvedi == -1 || (tkReturn != null && indexveve == -1))
                {
                    return (int)BookingStatus.NOTMACTHDEPART;// Không tìm được vé tương ứng
                }

                if (lstTickets[indexvedi].Price != tkDepart.Price)
                {
                    LogManager.GetInstance().Warn("Jetstart: " + BookingStatus.CHANGEDPRICE);


                    return (int)BookingStatus.CHANGEDPRICE;
                }

                if (tkReturn != null && lstTickets[indexveve].Price != tkReturn.Price)
                {
                    LogManager.GetInstance().Warn("Jetstart: " + BookingStatus.CHANGEDPRICE);

                    return (int)BookingStatus.CHANGEDPRICE;
                }

                #endregion

                #region 3.Chọn vé
                #region 3.1Điền thông tin hành lý
                string str_Bags = "";
                var totalTicket = passenges.Where(m => m.TypeID == 1 || m.TypeID == 2).ToArray();
                int ways = 1;
                if (tkReturn != null)
                    ways = 2;
                for (int x = 0; x < ways; x++)
                {
                    str_Bags += string.Format("&AgentAdditionalBaggagePassengerView%24AdditionalBaggageDropDownListJourney{0}={1}", x, "none");
                    for (int i = 0; i < totalTicket.Count(); i++)
                    {
                        string bg = "none";
                        if (x == 0 && totalTicket[i].BaggageDepartID > 0 && totalTicket[i].BaggageDepartValue > 0)
                        {
                            bg = "BG" + totalTicket[i].BaggageDepartValue;
                        }
                        if (x == 0 && isBackReturnToDepart && totalTicket[i].BaggageReturnID > 0 && totalTicket[i].BaggageReturnValue > 0)
                        {
                            bg = "BG" + totalTicket[i].BaggageReturnValue;
                        }
                        if (x == 1 && totalTicket[i].BaggageReturnID > 0 && totalTicket[i].BaggageReturnValue > 0)
                        {
                            bg = "BG" + totalTicket[i].BaggageReturnValue;
                        }
                        str_Bags += string.Format("&AgentAdditionalBaggagePassengerView%24AdditionalBaggageDropDownListJourney{0}Pax{1}={2}", x, i, bg);
                    }
                }
                //string strBG = string.Format("https://book.jetstar.com/AgentBaggageDetails.aspx?flightKeys={0}%2C{1}&numberOfmarkets={2}&keyDelimeter=%2C",
                //    indexvedi != -1 ? HttpUtility.UrlEncode(lstTickets[indexvedi].DataToBook) : "",//0
                //    indexveve != -1 ? HttpUtility.UrlEncode(lstTickets[indexveve].DataToBook) : "",//1
                //    tkReturn != null ? 2 : 1//2
                //    );

                //var resBG =  m_request.GetData(strBG);
                //if (resBG == null)
                //{
                //    LogManager.GetInstance().Error("Jetstart: Can not get baggage");
                //    return (int)BookingStatus.BAGGAGE_ERROR;
                //}

                //string strBGHTML = m_request.GetHtmlFromResponse(resBG);

                //if (string.IsNullOrEmpty(strBGHTML))
                //{
                //    LogManager.GetInstance().Error("Jetstart: Can not get baggage");
                //    return (int)BookingStatus.BAGGAGE_ERROR;
                //}

                #endregion
                string add3 = "https://book.jetstar.com/AgentSelect.aspx";
                string data3 = string.Format("__EVENTTARGET=ControlGroupAgentSelectView%24ButtonSubmit&__EVENTARGUMENT=&__VIEWSTATE={2}&pageToken=&total_price=29.470&ControlGroupAgentSelectView%24AvailabilityInputAgentSelectView%24HiddenFieldTabIndex1={5}&bannerFileName=&ControlGroupAgentSelectView%24AvailabilityInputAgentSelectView%24market1={0}&bannerFileName=&bannerFileName=&bannerFileName=&bannerFileName=&bannerFileName=&bannerFileName=&ControlGroupAgentSelectView%24AvailabilityInputAgentSelectView%24HiddenFieldTabIndex2={5}&bannerFileName=&ControlGroupAgentSelectView%24AvailabilityInputAgentSelectView%24market2={1}&bannerFileName=&bannerFileName=&bannerFileName=&bannerFileName=&bannerFileName=&baggage-selection-toggler=on{4}&marketstructure={3}",
                    indexvedi != -1 ? HttpUtility.UrlEncode(lstTickets[indexvedi].DataToBook) : "",//0
                    indexveve != -1 ? HttpUtility.UrlEncode(lstTickets[indexveve].DataToBook) : "",//1
                    HttpUtility.UrlEncode(m_strViewState),//2
                    strRound,//3
                    str_Bags,//4
                    "4"//5
                    );
                var respones = m_request.PostData(add3, data3);
                html = m_request.GetHtmlFromResponse(respones);
                lstResultHTML[add3] = html;
                if (html.IndexOf("AgentPassenger.aspx") == -1)
                {
                    LogManager.GetInstance().Warn("Jetstar: Try get " + add3);
                    respones = m_request.PostData(add3, data3);
                    html = m_request.GetHtmlFromResponse(respones);
                    lstResultHTML["_try_" + add3] = html;
                }
                if (html.IndexOf("AgentPassenger.aspx") == -1)
                {
                    LogManager.GetInstance().Error("Jetstar error: " + add3);

                    return (int)BookingStatus.BK_ERR_PASSENGER;
                }
                UpdateViewState(html);
                #endregion

                #region 4.Điền thông tin đặt vé

                string add4 = "https://book.jetstar.com/AgentPassenger.aspx";

                #region 4.0Khởi tạo thông tin

                string data4 = "__EVENTTARGET=AgentControlGroupPassengerView%24ButtonSubmit&__EVENTARGUMENT=&__VIEWSTATE=" + HttpUtility.UrlEncode(m_strViewState) + "&pageToken=&total_price=14.585";
                #endregion

                #region 4.1Điền thông tin đại lý

                string str_bookingInfo = string.Format("&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24DropDownListTitle=MR&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24TextBoxFirstName=LINH&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24TextBoxLastName=VU+THANH&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24DropDownListWorkPhoneCountryCode=VN&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24TextBoxWorkPhone={1}&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24TextBoxJahEmailAddress={0}&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24TextBoxEmailAddress={0}&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24TextBoxPostalCode=A&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24TextBoxCity=HCM&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24TextBoxAddressLine1=80+DINH+TIEN+HOANG+QBT&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24TextBoxAddressLine2=&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24TextBoxCompanyName=CTY+HOANG+GIANG+VIET&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24DropDownListCountry=VN&AgentControlGroupPassengerView%24AgentContactInputViewPassengerView%24DropDownListCountryCode=VN",
                    HttpUtility.UrlEncode(emailDefault),//0
                    booking.Phone
                    );

                #endregion

                #region 4.2Điền thông tin khách hàng bay

                string str_Aduts = "";
                string str_Babies = "";
                string str_Childs = "";

                var lstAduts = passenges.Where(m => m.TypeID == 1).ToList();
                var lstBabies = passenges.Where(m => m.TypeID == 3).ToList();
                int index = 0;
                int iPassenger = 1;
                for (index = 0; index < lstAduts.Count; index++)
                {
                    var nameSplit = lstAduts[index].Name.Split(' ');
                    string strName = nameSplit[nameSplit.Length - 1];
                    string fname = lstAduts[index].FirstName;
                    for (int i = 0; i < nameSplit.Length - 1; i++)
                    {
                        fname += " " + nameSplit[i];
                    }
                    str_Aduts += string.Format("&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListTitle_{7}={0}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24TextBoxFirstName_{7}={1}&default-value-firstname-{7}=T%C3%AAn&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24TextBoxLastName_{7}={2}&default-value-lastname-{7}=H%E1%BB%8D+v%C3%A0+t%C3%AAn+%C4%91%E1%BB%87m&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListBirthDateDay_{7}={4}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListBirthDateMonth_{7}={5}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListBirthDateYear_{7}={6}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListGender_{7}={3}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24TextBoxProgramNumber_{7}=&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListProgram_{7}=QF",
                 lstAduts[index].Sex == "M" ? "MR" : "MS",//0  M F
                 strName,//1
                 HttpUtility.UrlEncode(fname),//2
                 lstAduts[index].Sex == "M" ? "1" : "2",//0  M F,//3
                 lstAduts[index].Birthday != null ? lstAduts[index].Birthday.ToString("%d") : "",//4
                 lstAduts[index].Birthday != null ? lstAduts[index].Birthday.ToString("%M") : "",//5
                 lstAduts[index].Birthday != null ? lstAduts[index].Birthday.ToString("yyyy") : "",//6
                 iPassenger//7
                    );

                    iPassenger++;
                    if (lstBabies.Count > index)//nếu có em bé thì xen giữa người lớn
                    {
                        nameSplit = lstBabies[index].Name.Split(' ');
                        strName = nameSplit[nameSplit.Length - 1];
                        fname = lstBabies[index].FirstName;
                        for (int i = 0; i < nameSplit.Length - 1; i++)
                        {
                            fname += " " + nameSplit[i];
                        }

                        str_Babies += string.Format("&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24TextBoxFirstName_{0}={1}&default-value-firstname-{0}=T%C3%AAn&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24TextBoxLastName_{0}={2}&default-value-lastname-{0}=H%E1%BB%8D+v%C3%A0+t%C3%AAn+%C4%91%E1%BB%87m&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListAssign_{0}={3}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListBirthDateDay_{0}={4}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListBirthDateMonth_{0}={5}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListBirthDateYear_{0}={6}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListGender_{0}={7}",
                            iPassenger,//0
                            strName,//1
                            HttpUtility.UrlEncode(fname),//2
                            iPassenger / 2,//3 - vi tri nguoi lon
                            lstBabies[index].Birthday != null ? lstBabies[index].Birthday.ToString("%d") : "",//4
                            lstBabies[index].Birthday != null ? lstBabies[index].Birthday.ToString("%M") : "",//5
                            lstBabies[index].Birthday != null ? lstBabies[index].Birthday.ToString("yyyy") : "",//6
                            lstBabies[index].Sex == "M" ? "1" : "2"//0  M F  //7
                            );
                        iPassenger++;
                    }
                }
                var lstChilds = passenges.Where(m => m.TypeID == 2).ToList();
                index = 0;
                foreach (var child in lstChilds)
                {
                    var nameSplit = lstChilds[index].Name.Split(' ');
                    string strName = nameSplit[nameSplit.Length - 1];
                    string fname = lstChilds[index].FirstName;
                    for (int i = 0; i < nameSplit.Length - 1; i++)
                    {
                        fname += " " + nameSplit[i];
                    }
                    str_Childs += string.Format("&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListTitle_{7}={0}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24TextBoxFirstName_{7}={1}&default-value-firstname-{7}=T%C3%AAn&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24TextBoxLastName_{7}={2}&default-value-lastname-{7}=H%E1%BB%8D+v%C3%A0+t%C3%AAn+%C4%91%E1%BB%87m&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListBirthDateDay_{7}={4}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListBirthDateMonth_{7}={5}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListBirthDateYear_{7}={6}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListGender_{7}={3}&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24TextBoxProgramNumber_{7}=&AgentControlGroupPassengerView%24AgentPassengerInputViewPassengerView%24DropDownListProgram_{7}=QF",
                 lstChilds[index].Sex == "M" ? "MR" : "MS",//0  M F
                 strName,//1
                 HttpUtility.UrlEncode(fname),//2
                 lstChilds[index].Sex == "M" ? "1" : "2",//0  M F,//3
                 lstChilds[index].Birthday != null ? lstChilds[index].Birthday.ToString("%d") : "",//4
                 lstChilds[index].Birthday != null ? lstChilds[index].Birthday.ToString("%M") : "",//5
                 lstChilds[index].Birthday != null ? lstChilds[index].Birthday.ToString("yyyy") : "",//6
                 iPassenger//7
                    );
                    iPassenger++;
                    index++;
                }

                //add more

                string strMore = "&AgentControlGroupPassengerView%24AgentItineraryDistributionInputPassengerView%24Distribution=2";

                var lstSeat = passenges.Where(m => m.TypeID != 3).ToArray();

                for (int i = 0; i < lstSeat.Length; i++)
                {
                    strMore += string.Format("&AgentControlGroupPassengerView%24AgentUnitMapSeatsView%24HiddenEquipmentConfiguration_0_PassengerNumber_{0}=", i);
                    if (tkDepart != null)
                    {
                        strMore += string.Format("&AgentControlGroupPassengerView%24AgentUnitMapSeatsView%24HiddenEquipmentConfiguration_1_PassengerNumber_{0}=", i);
                    }
                }


                #endregion

                string strTempData = data4 + str_bookingInfo + str_Aduts + str_Childs + str_Babies + strMore;
                respones = m_request.PostData(add4, strTempData);
                html = m_request.GetHtmlFromResponse(respones);
                lstResultHTML[add4] = html;
                if (respones.ResponseUri.AbsoluteUri.IndexOf("https://book.jetstar.com/AgentPay.aspx") == -1)
                {
                    LogManager.GetInstance().Warn("Jetstar: Try get " + add4);
                    respones = m_request.PostData(add4, data4 + str_bookingInfo + str_Aduts + str_Childs + str_Babies + strMore);
                    html = m_request.GetHtmlFromResponse(respones);
                    lstResultHTML["_try_" + add4] = html;
                }
                if (respones.ResponseUri.AbsoluteUri.IndexOf("https://book.jetstar.com/AgentPay.aspx") == -1)
                {
                    LogManager.GetInstance().Error("Jetstar error: Try get " + add4);

                    return (int)BookingStatus.BK_ERR_GET_SEAT;
                }


                UpdateViewState(html);
                #endregion

                #region 7.Thanh toán

                string add7 = "https://book.jetstar.com/AgentPay.aspx";
                string data7 = string.Format("__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE={0}&pageToken=&total_price=14.585&ControlGroupAgentPayView%24PaymentSectionAgentPayView%24UpdatePanelAgentPayView%24PaymentInputAgentPayView%24PaymentMethodDropDown=ExternalAccount-HOLD&card_number1=&card_number2=&card_number3=&card_number4=&ControlGroupAgentPayView%24PaymentSectionAgentPayView%24UpdatePanelAgentPayView%24PaymentInputAgentPayView%24TextBoxCC__AccountHolderName=&ControlGroupAgentPayView%24PaymentSectionAgentPayView%24UpdatePanelAgentPayView%24PaymentInputAgentPayView%24DropDownListEXPDAT_Month=05&ControlGroupAgentPayView%24PaymentSectionAgentPayView%24UpdatePanelAgentPayView%24PaymentInputAgentPayView%24DropDownListEXPDAT_Year=2014&ControlGroupAgentPayView%24PaymentSectionAgentPayView%24UpdatePanelAgentPayView%24PaymentInputAgentPayView%24TextBoxCC__VerificationCode=&ControlGroupAgentPayView%24PaymentSectionAgentPayView%24UpdatePanelAgentPayView%24PaymentInputAgentPayView%24TextBoxACCTNO=&inlineDCCAjaxSucceeded=false&ControlGroupAgentPayView%24PaymentSectionAgentPayView%24UpdatePanelAgentPayView%24PaymentInputAgentPayView%24TextBoxVoucherAccount_VO_ACCTNO=&ControlGroupAgentPayView%24AgreementInputAgentPayView%24CheckBoxAgreement=on&ControlGroupAgentPayView%24ButtonSubmit=", viewstate);
                respones = m_request.PostData(add7, data7);
                html = m_request.GetHtmlFromResponse(respones);
                lstResultHTML[add7] = html;
                if (respones.ResponseUri.AbsoluteUri.IndexOf("https://book.jetstar.com/Wait.aspx") == -1)
                {
                    LogManager.GetInstance().Warn("Jetstar: Try get " + add7);
                    respones = m_request.PostData(add7, data7);
                    html = m_request.GetHtmlFromResponse(respones);
                    lstResultHTML[add7] = html;
                }
                if (respones.ResponseUri.AbsoluteUri.IndexOf("https://book.jetstar.com/Wait.aspx") == -1)
                {
                    LogManager.GetInstance().Error("Jetstar error: Try get " + add7);

                    return (int)BookingStatus.BK_ERR_CHECKOUT;
                }


                UpdateViewState(html);
                #endregion

                #region 8.Xác nhận thanh toán

                string add8 = "https://book.jetstar.com/Wait.aspx";
                respones = m_request.GetData(add8);
                html = m_request.GetHtmlFromResponse(respones);
                lstResultHTML[add8] = html;
                if (respones.ResponseUri.AbsoluteUri.IndexOf("https://book.jetstar.com/htl2-Itinerary.aspx") == -1)
                {
                    LogManager.GetInstance().Warn("Jetstar: Try get " + add8);
                    respones = m_request.GetData(add8);
                    html = m_request.GetHtmlFromResponse(respones);
                    lstResultHTML["_try_" + add8] = html;
                }
                if (respones.ResponseUri.AbsoluteUri.IndexOf("https://book.jetstar.com/htl2-Itinerary.aspx") == -1)
                {
                    LogManager.GetInstance().Error("Jetstar erro: Try get " + add8);

                    return (int)BookingStatus.BK_ERR_GET_BILL;
                }

                UpdateViewState(html);
                #endregion

                #region 9.Lấy thông tin đặt vé
                //respones = m_request.GetData("https://book.jetstar.com/htl2-Itinerary.aspx");
                //html = m_request.GetHtmlFromResponse(respones);
                GetThongTinSauKhiDatVe(html);
                #endregion

                LogManager.GetInstance().Info("Jetstart: Booking OK");

                return (int)BookingStatus.BOOKED;
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Jetstart: unsuccessfull", ex);
                return (int)BookingStatus.UNKNOW;
            }
            finally
            {
                if (string.IsNullOrEmpty(GetCode()))
                    this.SaveHTML(booking, lstResultHTML);
            }
        }

        private void SaveHTML(BK_Booking booking, Dictionary<string, string> lstResultHTML)
        {
            int index = 1;
            foreach (var item in lstResultHTML)
            {
                FileHelper.WriteFile(item.Value, "BookingLogFiles", "ERROR_" + DateTime.Now.ToString("dd_MM_HH_mm_")
                    + booking.Phone + "_" + index + item.Key
                    + ".html");
                index++;
            }
        }

        private void UpdateViewState(string html)
        {
            try
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);
                var nodesviewstate = doc.DocumentNode.SelectNodes("//*[@id=\"viewState\"]");
                m_strViewState = nodesviewstate[0].Attributes["value"].Value;
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Jetstart: UpdateViewState error", ex);
            }

        }
        List<BK_Ticket> Get(string htmlRespone, DateTime? _dtDateTo)
        {
            var lstResult = new List<BK_Ticket>();

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(htmlRespone);
            //get viewstate
            var nodesviewstate = doc.DocumentNode.SelectNodes("//*[@id=\"viewState\"]");
            m_strViewState = nodesviewstate[0].Attributes["value"].Value;


            //kiểm tra tìm vé không thành công
            var travles = doc.DocumentNode.SelectNodes("//*[@class=\"domestic\"]");
            if (travles.Count > 0)
            {
                //từng lượt
                int i = 0;
                foreach (var travel in travles)
                {
                    HtmlDocument docDepart = new HtmlDocument();
                    docDepart.LoadHtml(travel.InnerHtml);
                    var tickets = docDepart.DocumentNode.SelectNodes("//input[@type=\"radio\"]");
                    //từng vé
                    foreach (var ticket in tickets)
                    {
                        BK_Ticket t = new BK_Ticket();
                        if (ticket.Attributes["value"].Value == null)
                            continue;
                        string strInfo = ticket.Attributes["value"].Value;

                        t.DataToBook = strInfo;
                        //time.Replace(" ","");
                        strInfo = strInfo.Substring(strInfo.IndexOf('|') + 1);
                        string price = ticket.Attributes["data-price"].Value;
                        //BL~ 597~ ~~DAD~12/25/2013 22:00~SGN~12/25/2013 23:15~
                        //0    1      4       5             6      7  
                        string[] arrTemp = strInfo.Split('~');

                        t.EndDate = DateTime.ParseExact(arrTemp[7], "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                        t.StartDate = DateTime.ParseExact(arrTemp[5], "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                        t.FlightNo = arrTemp[0] + arrTemp[1];
                        t.FromCity = arrTemp[4];
                        t.LastUpdate = DateTime.Now;
                        t.ReturnDate = _dtDateTo != null ? _dtDateTo.Value.ToString("dd/MM/yyyy") : "";
                        t.ToCity = arrTemp[6];
                        t.Price = Int32.Parse(price.Substring(0, price.IndexOf('.')));
                        if (i == 0)
                            t.TypeWay = "Out";
                        if (i == 1)
                            t.TypeWay = "In";
                        lstResult.Add(t);
                    }
                    i++;
                }
            }
            if (lstResult != null)
            {
                //CacheManager.GetInstance().Add(strKeyword, lstResult.ToList());
            }
            //m_log.Info("Return " + lstResult.Count +" results");
            return lstResult;
        }

        /// <summary>
        /// Search tickets
        /// </summary>
        /// <param name="_strStationForm"></param>
        /// <param name="_strStationTo"></param>
        /// <param name="_dtDateFrom"></param>
        /// <param name="_dtDateTo"></param>
        /// <param name="_iAdut"></param>
        /// <param name="_iChild"></param>
        /// <param name="_iBaby"></param>
        /// <returns></returns>
        /// 


        public List<BK_Ticket> Search(string _strStationForm, string _strStationTo, DateTime _dtDateFrom, DateTime? _dtDateTo,
          int _iAdut, int _iChild, int _iBaby, bool _isInter, int _iUserID)
        {
            string strKeyword = "JetstarBoot_Search" + _strStationForm + "_" + _strStationTo + _dtDateFrom.ToString("_MM_dd_yyyy") +
                (_dtDateTo != null ? _dtDateTo.Value.ToString("_MM_dd_yyyy") : "") + _iAdut.ToString() + _iChild.ToString() + _iBaby.ToString() + "_User_" + _iUserID;
            //m_log.Info("Search: " + strKeyword);
            var cacheResult = CacheManager.GetInstance().Get(strKeyword);
            if (cacheResult != null)
            {
                //m_log.Info("Get from cache");
                return (List<BK_Ticket>)cacheResult;
            }
            var lstResult = new List<BK_Ticket>();

            Requester rq = m_request;

            string strReturnDay = _dtDateTo != null ? _dtDateTo.Value.Day.ToString() : "";
            string strReturnMonth = _dtDateTo != null ? _dtDateTo.Value.ToString("dd%2FMM%2Fyyyy") : "1968-1";
            string strRound = _dtDateTo != null ? "RoundTrip" : "OneWay";
            if (!this.Login())
            {
                LogManager.GetInstance().Error("Jetstar: Couldn't login");
                return lstResult;
            }
            string strTemp = string.Format("__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUBMGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFL01lbWJlckxvZ2luVHJhZGVTYWxlc0hvbWVWaWV3JG1lbWJlcl9SZW1lbWJlcm1l21vfn8zBj2cdGkkelpTFsbhWD1E%3D&pageToken=&total_price=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24RadioButtonMarketStructure={0}&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMarketOrigin1=Tp.H%E1%BB%93+Ch%C3%AD+Minh+%28{1}%29&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMarketDestination1=H%C3%A0+N%E1%BB%99i+%28{2}%29&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDepartureDate1={3}&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDestinationDate1={4}&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMarketOrigin2=H%C3%A0+N%E1%BB%99i+%28HAN%29&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMarketDestination2=Th%C3%A0nh+ph%E1%BB%91+H%E1%BB%93+Ch%C3%AD+Minh+%28SGN%29&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDepartureDate2={4}&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDestinationDate2=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMarketOrigin3=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMarketDestination3=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDepartureDate3=12%2F06%2F2014&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDestinationDate3=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMarketOrigin4=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMarketDestination4=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDepartureDate4=19%2F06%2F2014&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDestinationDate4=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMarketOrigin5=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMarketDestination5=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDepartureDate5=26%2F06%2F2014&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDestinationDate5=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMarketOrigin6=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMarketDestination6=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDepartureDate6=03%2F07%2F2014&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDestinationDate6=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24DropDownListPassengerType_ADT={5}&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24DropDownListPassengerType_CHD={6}&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24DropDownListPassengerType_INFANT={7}&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMultiCityOrigin1=T%E1%BB%AB&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMultiCityDestination1=D%E1%BA%BFn&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDepartureMultiDate1=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMultiCityOrigin2=T%E1%BB%AB&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextBoxMultiCityDestination2=D%E1%BA%BFn&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24TextboxDepartureMultiDate2=&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24DropDownListMultiPassengerType_ADT=1&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24DropDownListMultiPassengerType_CHD=0&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24DropDownListMultiPassengerType_INFANT=0&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24numberTrips=2&ControlGroupTradeSalesHomeView%24AvailabilitySearchInputTradeSalesHomeView%24ButtonSubmit=",
                strRound,//0
                _strStationForm,//1
                _strStationTo,//2
                string.Format("{0}%2F{1}%2F{2}", _dtDateFrom.ToString("dd"), _dtDateFrom.ToString("MM"), _dtDateFrom.ToString("yyyy")),//05%2F01%2F2014 //3
                _dtDateTo != null ? string.Format("{0}%2F{1}%2F{2}", _dtDateTo.Value.ToString("dd"), _dtDateTo.Value.ToString("MM"), _dtDateTo.Value.ToString("yyyy")) : "",//05%2F01%2F2014   //4
                 _iAdut, //5
                _iChild,//6
                _iBaby//7
                );

            //http://book.jetstar.com/Search.aspx?culture=vi-VN
            string strLink = "https://book.jetstar.com/TradeSalesHome.aspx";
            var respone = rq.PostData(strLink, strTemp);

            string htmlRespone = rq.GetHtmlFromResponse(respone);
            html = htmlRespone;
            lstResultHTML[strLink] = html;
            #region Try login

            if (html.IndexOf("logout") == -1)
            {
                LogManager.GetInstance().Error("Jetstar: Login failed!");
                return lstResult;
            }
            #endregion
            if (html.IndexOf("AgentSelect.aspx") == -1)
            {
                LogManager.GetInstance().Error("Jetstar: Can't find tickets");
                respone = rq.PostData(strLink, strTemp);
                htmlRespone = rq.GetHtmlFromResponse(respone);
                html = htmlRespone;
                lstResultHTML["_try_" + strLink] = html;
            }

            UpdateViewState(htmlRespone);
            //var htmlRespone = System.IO.File.ReadAllText(@"C:\PROJECTS\TheGioiVeRe\Sources\TGVR-Project\TGVR_Boot\bin\Debug\resultsearch.html");
            if (respone != null)
            {

                {
                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(htmlRespone);
                    //get viewstate
                    var nodesviewstate = doc.DocumentNode.SelectNodes("//*[@id=\"viewState\"]");
                    m_strViewState = nodesviewstate[0].Attributes["value"].Value;

                    //kiểm tra tìm vé không thành công
                    var travles = doc.DocumentNode.SelectNodes("//*[@class=\"section fare-option\"]");

                    if (travles == null)
                    {
                        return lstResult;
                    }
                    if (travles.Count > 0)
                    {
                        string strFee = "FeeJetstar";
                        if (_isInter)
                            strFee = "FeeJetstarInter";
                        var iFee = Int32.Parse(SettingBUS.Current.GetSetting(_iUserID, strFee).Value);

                        //var iFeeHotSaleJet = Int32.Parse(new SettingDAO(_iUserID).GetSetting("FeeHotSaleJet"));
                        var iDollar = Int32.Parse(SettingBUS.Current.GetSetting(_iUserID, "Dollar").Value);
                        var vnFirm = TK_FirmBUS.Current.GetFirmByShortName("BL");
                        //HotSaleJet
                        //từng lượt
                        int i = 0;
                        foreach (var travel in travles)
                        {
                            HtmlDocument docDepart = new HtmlDocument();
                            docDepart.LoadHtml(travel.InnerHtml);

                            var tickets = docDepart.DocumentNode.SelectNodes("//input[@type=\"radio\"]");
                            var rows = docDepart.DocumentNode.SelectNodes("//tr");
                            int iRow = 0;
                            if (tickets == null)
                                continue;
                            //từng vé
                            foreach (var ticket in tickets)
                            {
                                BK_Ticket t = new BK_Ticket();
                                t.Profit = iFee;
                                t.ChildPricePercent = vnFirm.Child;
                                t.BabyPricePercent = vnFirm.Baby;
                                t.IsInter = _isInter;
                                t.AirType = "jetstar";
                                //bool isSale = rows[iRow].InnerHtml.IndexOf("sale jquery-sale") > -1;
                                iRow++;
                                //t.IsHotSale = isSale;
                                if (ticket.Attributes["value"].Value == null)
                                    continue;
                                string strInfo = ticket.Attributes["value"].Value;
                                if (strInfo.IndexOf(_strStationForm) == -1 || strInfo.IndexOf(_strStationTo) == -1)
                                {
                                    throw new Exception("Tìm sai chuyến bay");
                                }
                                t.DataToBook = strInfo;
                                //time.Replace(" ","");
                                strInfo = strInfo.Substring(strInfo.IndexOf('|') + 1);
                                string price = ticket.Attributes["data-price"].Value;


                                //BL~ 597~ ~~DAD~12/25/2013 22:00~SGN~12/25/2013 23:15~
                                //0    1      4       5             6      7  
                                string[] arrTemp = strInfo.Split('~');

                                t.EndDate = DateTime.ParseExact(arrTemp[7], "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                t.StartDate = DateTime.ParseExact(arrTemp[5], "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                t.FlightNo = arrTemp[0] + arrTemp[1];
                                if (lstResult.Exists(m => m.StartDate == t.StartDate))
                                    continue;
                                t.FromCity = arrTemp[4];
                                t.LastUpdate = DateTime.Now;
                                t.ReturnDate = _dtDateTo != null ? _dtDateTo.Value.ToString("dd/MM/yyyy") : "";
                                t.ToCity = arrTemp[6];
                                //Bỏ qua chặng 2 chiều
                                if ((t.FromCity != _strStationForm && t.ToCity != _strStationForm) || (t.FromCity != _strStationTo && t.ToCity != _strStationTo))
                                {
                                    continue;
                                }
                                t.PriceBefore = Int32.Parse(price.Substring(0, price.IndexOf('.')));

                                if (_isInter)
                                {
                                    t.Price = t.PriceBefore;
                                    //data-fees-adt
                                    string feeOnWeb = ticket.Attributes["data-fees-adt"].Value;
                                    feeOnWeb = feeOnWeb.Substring(0, feeOnWeb.IndexOf('.'));
                                    t.Price += Int32.Parse(feeOnWeb) + iFee;
                                }
                                else
                                {
                                    t.Price = (int)(1.1 * (float)t.PriceBefore);
                                    t.Price += 100000 + iFee;
                                }
                                //if (t.IsHotSale)
                                //    t.Price += iFeeHotSaleJet;
                                if (t.FromCity == _strStationForm)
                                    t.TypeWay = "Out";

                                if (_dtDateTo.HasValue && t.FromCity == _strStationTo)
                                    t.TypeWay = "In";
                                t.Image = "http://thegioivere.net/content/images/logo/BL.png";

                                //Holding time
                                //Jetstar : cach gio bay 48h
                                t.HoldToDate = DateTime.Now.AddHours(24);
                                if (t.HoldToDate > t.StartDate.AddHours(-12))//
                                {
                                    t.HoldToDate = t.StartDate.AddHours(-12);
                                    if (t.HoldToDate < DateTime.Now)
                                        t.HoldToDate = DateTime.Now;
                                }

                                lstResult.Add(t);
                            }
                            i++;
                        }
                    }
                    if (lstResult != null && lstResult.Count > 0)
                    {
                        CacheManager.GetInstance().Add(strKeyword, lstResult.ToList());
                    }
                    //m_log.Info("Return " + lstResult.Count +" results");
                    return lstResult;
                }
            }
            return null;
        }

        public List<BK_Ticket> SearchCheapest(string _strStationForm, string _strStationTo, DateTime _dtDateFrom, DateTime? _dtDateTo,
            int _iAdut, int _iChild, int _iBaby, int _iUserID)
        {
            string strKeyword = "JetstarBootSearchCheapest" + _strStationForm + _strStationTo + _dtDateFrom.ToString("MMyyyy") +
                    (_dtDateTo != null ? _dtDateTo.Value.ToString("MMyyyy") : "") + _iAdut.ToString() + _iChild.ToString() + _iBaby.ToString() + "_User" + _iUserID;
            //m_log.Info("Search: " + strKeyword);
            //var cacheResult = CacheManager.GetInstance().Get(strKeyword);
            var cacheResult = CacheManager.GetInstance().Get(strKeyword);
            //CacheManager.GetInstance().Add(strKeyword, lstResult.ToList());
            if (cacheResult != null)
            {
                //m_log.Info("Get from cache");
                return (List<BK_Ticket>)cacheResult;
            }

            WorkerManager wkBus = new WorkerManager();

            if (_dtDateFrom.Year == DateTime.Now.Year//kiểm tra cùng tháng
                && _dtDateFrom.Month == DateTime.Now.Month
                && DateTime.Now.Day > 3
                && (!_dtDateTo.HasValue ||
                        (
                            _dtDateTo.Value.Year == _dtDateTo.Value.Year
                            && _dtDateTo.Value.Month == _dtDateTo.Value.Month
                        )
                    )
              )
            {
                if (DateTime.Now.Day < 17)
                {
                    _dtDateFrom = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 17);
                    if (_dtDateTo != null)
                        _dtDateTo = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 17);
                }
                else
                {
                    _dtDateFrom = DateTime.Now;
                    if (_dtDateTo != null)
                        _dtDateTo = DateTime.Now;
                }

                wkBus.Add(new FindCheapestWorkerJET("JetstarPart1", new JetstarBoot(), ComineTickets, _strStationForm, _strStationTo, _dtDateFrom, _dtDateTo, _iAdut, _iChild, _iBaby, _iUserID));
            }
            else
            {
                //lần 1
                _dtDateFrom = new DateTime(_dtDateFrom.Year, _dtDateFrom.Month, 14);
                if (_dtDateTo != null)
                    _dtDateTo = new DateTime(_dtDateTo.Value.Year, _dtDateTo.Value.Month, 14);

                wkBus.Add(new FindCheapestWorkerJET("JetstarPart1", new JetstarBoot(), ComineTickets, _strStationForm, _strStationTo, _dtDateFrom, _dtDateTo, _iAdut, _iChild, _iBaby, _iUserID));

                //lần 2
                _dtDateFrom = new DateTime(_dtDateFrom.Year, _dtDateFrom.Month, 17);
                if (_dtDateTo != null)
                    _dtDateTo = new DateTime(_dtDateTo.Value.Year, _dtDateTo.Value.Month, 17);

                wkBus.Add(new FindCheapestWorkerJET("JetstarPart2", new JetstarBoot(), ComineTickets1, _strStationForm, _strStationTo, _dtDateFrom, _dtDateTo, _iAdut, _iChild, _iBaby, _iUserID));
            }

            wkBus.Run();

            lstResult.AddRange(lstResult1.Where(m => m.StartDate.Day > 28));
            if (lstResult != null)
            {
                //CacheManager.GetInstance().Add(strKeyword, lstResult.ToList());
                CacheManager.GetInstance().Add(strKeyword, lstResult.ToList());
            }
            return lstResult;
        }

        private List<BK_Ticket> lstResult1 = new List<BK_Ticket>();
        private List<BK_Ticket> lstResult = new List<BK_Ticket>();

        private void ComineTickets(object data)
        {
            try
            {
                this.lstResult.AddRange((List<BK_Ticket>)data);
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("JestarAir: Lỗi tìm vé rẻ trong tháng", ex);
            }
        }

        private void ComineTickets1(object data)
        {
            try
            {
                this.lstResult1.AddRange((List<BK_Ticket>)data);
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("JestarAir: Lỗi tìm vé rẻ trong tháng", ex);
            }
        }

        public List<BK_Ticket> SearchCheapestPart1(string _strStationForm, string _strStationTo, DateTime _dtDateFrom, DateTime? _dtDateTo,
            int _iAdut, int _iChild, int _iBaby, int _iUserID)
        {

            string htmlResult = "";// File.ReadAllText(@"C:\PROJECTS\TheGioiVeRe\Documents\Searching\Cheapest\jet.html");
            if (htmlResult == "")
            {
                Requester rq = m_request;

                string strReturnDay = _dtDateTo != null ? _dtDateTo.Value.Day.ToString() : "";
                string strReturnMonth = _dtDateTo != null ? _dtDateTo.Value.ToString("MM") : "";
                string strReturnYear = _dtDateTo != null ? _dtDateTo.Value.ToString("yyyy") : "";
                string strRound = _dtDateTo != null ? "RoundTrip" : "OneWay";

                string strRequest = string.Format("http://book.jetstar.com/lowfarefinder.aspx?culture=vi-VN&RadioButtonMarketStructure={0}&Origin1={1}&Destination1={2}&Day1={3}&MonthYear1={4}-{5}&Origin2={2}&Destination2={1}&Day2={6}&MonthYear2={7}-{11}&ADT={8}&CHD={9}&INFANT={10}&AutoSubmit=Y&ControlGroupCalendarSearchView$AvailabilitySearchInputCalendarSearchView$DropDownListCurrency=VND",
                    strRound, //0
                    _strStationForm,//1
                    _strStationTo,//2
                    _dtDateFrom.ToString("%d"),//3
                    _dtDateFrom.ToString("yyyy"),//4
                    _dtDateFrom.ToString("%M"),//5
                    strReturnDay,//6
                    strReturnYear,//7
                    _iAdut,//8
                    _iChild,//9
                    _iBaby,//10
                     strReturnMonth//7
                    );
                Requester re = new Requester();
                var res = re.GetData(strRequest);
                htmlResult = re.GetHtmlFromResponse(res);
            }


            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(htmlResult);
            var travels = doc.DocumentNode.SelectNodes("//*[@class=\"low-fare-selector\"]");
            if (_dtDateTo != null && travels.Count != 2)
                throw new Exception("Không tìm dc lượt về");
            List<BK_Ticket> lstResult = new List<BK_Ticket>();
            var iFee = Int32.Parse(SettingBUS.Current.GetSetting(_iUserID, "FeeJetstar").Value);
            for (int i = 0; i < travels.Count; i++)
            {
                HtmlDocument doctds = new HtmlDocument();
                doctds.LoadHtml(travels[i].InnerHtml);
                var tickets = doctds.DocumentNode.SelectNodes("//li");
                foreach (var ticket in tickets)
                {
                    BK_Ticket t = new BK_Ticket();
                    t.AirType = "jetstar";
                    string strDate = ticket.Attributes["data-date"].Value;
                    t.StartDate = DateTime.ParseExact(strDate, "d/M/yyyy", CultureInfo.InvariantCulture);
                    t.EndDate = t.StartDate;

                    string strPrice = ticket.Attributes["data-price"].Value;
                    if (strPrice == "")
                        strPrice = "0";
                    t.PriceBefore = Int32.Parse(strPrice);
                    t.Price = (int)(1.1 * (float)t.PriceBefore);
                    t.Price += 100000 + iFee;
                    t.FlightNo = "BL";
                    t.FromCity = _strStationForm;
                    t.ToCity = _strStationTo;
                    t.Image = "http://thegioivere.net/content/images/logo/BL.png";
                    lstResult.Add(t);
                    t.TypeWay = i == 0 ? "Out" : "In";
                }
            }

            return lstResult;
        }


        public decimal GetOutputFee(decimal TotalPrice, DateTime StartDate)
        {
            return 0;
        }

    }
}
